import type { Response } from "@/types/response";
import useLoginStore from "@/pinia/modules/loginStore";

// 请求基础地址
const baseUrl: string = "https://pcapi-xiaotuxian-front-devtest.itheima.net";
//拦截器
const httpInterceptor: UniApp.InterceptorOptions = {
   invoke(options: UniApp.RequestOptions): void {
      uni.showLoading({
         title: "Loading···",
      });
      // 如果不是http开头则添加请求基础地址
      if (!options.url.startsWith("https") || !options.url.startsWith("http")) {
         options.url = baseUrl + options.url;
      }
      // 超时时间
      options.timeout = 100000;
      // 请求头
      // #ifdef MP-WEIXIN
      options.header = {
         ...options.header,
         "source-client": "miniapp",
      };
      // #endif

      // #ifndef MP-WEIXIN
      options.header = {
         ...options.header,
         "source-client": "app",
      };
      // #endif

      const loginStore=useLoginStore()
      if (loginStore.userInfo.token){
         options.header={
            Authorization: loginStore.userInfo.token
         }
      }
   },
   success(): void {
   },
   fail(): void {
   },
   complete(): void {
      uni.hideLoading();
   },
};
// 请求函数
const request = <T>(options: UniApp.RequestOptions) => {
   return new Promise<Response<T>>((resolve, reject): void => {
      uni.request({
         ...options,
         success(result: UniApp.RequestSuccessCallbackResult): void {
            const code: number = result.statusCode;
            const data: Response<T> = result.data as Response<T>;
            if (code >= 200 && code < 300) {
               resolve(data);
            } else if (code === 401) {
               reject(Promise.reject(new Error(data.msg)));
            } else {
               reject(Promise.reject(new Error(data.msg)));
            }
         },
         fail(error: UniApp.GeneralCallbackResult) {
            reject(Promise.reject(new Error("网络错误")));
         },
         complete() {

         },
      });
   });
};
// 拦截request、uploadFile请求
uni.addInterceptor("request", httpInterceptor);
uni.addInterceptor("uploadFile", httpInterceptor);

export default request;